<?php
/**
 * OSS使用类
 * @Author    紫梦
 * @DateTime  2017-12-19
 * @copyright 响响租车
 * @version   1.0
 */
namespace app\common\request;

use OSS\OssClient;
use OSS\Core\OssException;
class Oss
{

	protected $ossClient;
	protected $config;
	/**
     * @function    构造方法
     * @param null
     * @return object
     * @user    allen
     * @date    2016/10/18   11:43
     */
    public function __construct()
    {
		//获取配置项，并赋值给对象$config
	    $this->config = config('aliyun_oss');
	    //实例化OSS
	    $this->ossClient = new OssClient($this->config['KeyId'],$this->config['KeySecret'],$this->config['Endpoint']);
	}

	/**
	 * OSS上传并删除本地文件
	 */
	public function uploadOss($file)
	{
		$info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
        if($info){
            // 成功上传后 获取上传信息
            $url = $info->getSaveName();
            $path = ROOT_PATH . 'public' . DS . 'uploads/'.$url;
            $object = 'record/uploads/'.$url;
            // 上传到OSS
            try {
                $this->ossClient->uploadFile($this->config['Bucket'], $object, $path);

            } catch (OssException $e) {
                printf(__FUNCTION__ . ": FAILED\n");
                printf($e->getMessage() . "\n");
                return;
            }
           	//关闭文件对象并删除本地文件
            $info = null;
            unlink($path); 

        }else{
  			return false;

        }
        return $url;
	}

    /**
     * 删除文件
     */
    
    public function unlinkOss($url)
    {
        $object = 'record/uploads/'.$url;
        try{
            $this->ossClient->deleteObject($this->config['Bucket'], $object);
        } catch(OssException $e) {
            printf(__FUNCTION__ . ": FAILED\n");
            printf($e->getMessage() . "\n");
            return;
        }
        return true;
    }

}